#include "accountmanager.h"
#include <QtSql/QSqlDatabase>
#include <QtSql/QSqlQuery>
#include <QtSql/QSqlError>
#include <QCryptographicHash>
#include <QDebug>
#include "journeymodels.h"


QSqlDatabase AccountManager::db = QSqlDatabase::addDatabase("QSQLITE", "FlightSystemConnection");

AccountManager::AccountManager() {


    if (!db.isOpen()) {
        db.setDatabaseName("flightsystem.db");
        if (!db.open()) {
            qDebug() << "Database connection failed: " << db.lastError().text();
        }

        qDebug() << "Database opened successfully at: " << db.databaseName();
        // 创建 users 表
        QSqlQuery query(db);

        query.exec("PRAGMA foreign_keys = ON;");

        if (!query.exec("CREATE TABLE IF NOT EXISTS users ("
                        "id INTEGER PRIMARY KEY AUTOINCREMENT, "
                        "username TEXT UNIQUE, "
                        "password TEXT, "
                        "contact TEXT)")) {
            qDebug() << "Failed to create users table: " << query.lastError().text();
        }

        // 创建 user_bookings 表
        if (!query.exec("CREATE TABLE IF NOT EXISTS user_bookings ("
                        "booking_id INTEGER PRIMARY KEY AUTOINCREMENT, "
                        "user_id INTEGER, "                    
                        "journey_id INTEGER, "
                        "booking_time TEXT, "                       
                        "FOREIGN KEY(user_id) REFERENCES users(id) ON DELETE CASCADE, "
                        "FOREIGN KEY(journey_id) REFERENCES journeys(journey_id) ON DELETE CASCADE)")) {
            qDebug() << "Failed to create user_bookings table: " << query.lastError().text();
        }

        // 创建 journeys 表
        if (!query.exec("CREATE TABLE IF NOT EXISTS journeys ("
                        "journey_id INTEGER PRIMARY KEY AUTOINCREMENT, "
                        "start_city TEXT, "
                        "end_city TEXT, "
                        "total_price REAL, "
                        "total_time INTEGER, "
                        "user_id INTEGER, "
                        "FOREIGN KEY(user_id) REFERENCES users(id))")) {
            qDebug() << "Failed to create journeys table: " << query.lastError().text();
        }

        // 创建 flight_segments 表
        if (!query.exec("CREATE TABLE IF NOT EXISTS flight_segments ("
                        "segment_id INTEGER PRIMARY KEY AUTOINCREMENT, "
                        "journey_id INTEGER, "
                        "from_city TEXT, "
                        "to_city TEXT, "
                        "flight_number TEXT, "
                        "airline TEXT, "
                        "departure_airport TEXT, "
                        "arrival_airport TEXT, "
                        "departure_time TEXT, "
                        "arrival_time TEXT, "
                        "price REAL, "
                        "is_transfer TEXT, "
                        "FOREIGN KEY(journey_id) REFERENCES journeys(journey_id) ON DELETE CASCADE)")) {
            qDebug() << "Failed to create flight_segments table: " << query.lastError().text();
        }
    }
}

QSqlDatabase& AccountManager::getDatabase() {
    // 如果数据库还没有打开，尝试打开数据库
    if (!db.isOpen()) {
        db.setDatabaseName("flightsystem.db");
        if (!db.open()) {
            qDebug() << "Database connection failed: " << db.lastError().text();
        } else {
            qDebug() << "Database connection established.";
        }
    }
    return db;
}



void AccountManager::setupUserManagementButton(QMainWindow* mainWindow) {
    userManagementButton = new QPushButton("用户管理", mainWindow);
    userManagementButton->setGeometry(mainWindow->width() - 150, 10, 120, 30);
    QObject::connect(userManagementButton, &QPushButton::clicked, [mainWindow]() {
        UserManagementWidget* userWidget = new UserManagementWidget(mainWindow);
        userWidget->setAttribute(Qt::WA_DeleteOnClose);
        userWidget->show();
    });
}


bool AccountManager::registerUser(const QString& username, const QString& password, const QString& contact) {
    // 最大字符限制
    const int maxUsernameLength = 10;
    const int maxPasswordLength = 64;
    const int maxContactLength = 20;

    // 检查用户名长度
    if (username.length() > maxUsernameLength) {
        QMessageBox::warning(nullptr, "注册失败", QString("用户名长度不能超过 %1 个字符").arg(maxUsernameLength));
        return false;
    }

    // 检查密码长度
    if (password.length() > maxPasswordLength) {
        QMessageBox::warning(nullptr, "注册失败", QString("密码长度不能超过 %1 个字符").arg(maxPasswordLength));
        return false;
    }

    // 检查联系方式长度
    if (contact.length() > maxContactLength) {
        QMessageBox::warning(nullptr, "注册失败", QString("联系方式长度不能超过 %1 个字符").arg(maxContactLength));
        return false;
    }

    // 检查数据库连接
    if (!db.isOpen() && !db.open()) {
        QMessageBox::critical(nullptr, "数据库错误", "无法连接到数据库，请稍后再试！");
        return false;
    }

    // 检查用户名是否存在
    if (userExists(username)) {
        QMessageBox::warning(nullptr, "注册失败", "注册失败，用户名可能已存在");
        return false;
    }

    // 哈希密码
    QString hashedPassword = hashPassword(password);

    // 插入新用户
    QSqlQuery query(db);
    query.prepare("INSERT INTO users (username, password, contact) VALUES (?, ?, ?)");
    query.addBindValue(username);
    query.addBindValue(hashedPassword);
    query.addBindValue(contact);

    if (!query.exec()) {
        QMessageBox::critical(nullptr, "注册失败", QString("注册失败: %1").arg(query.lastError().text()));
        return false;
    }

    QMessageBox::information(nullptr, "注册成功", "用户注册成功！");
    return true;
}



QString AccountManager::loginUser(const QString& username, const QString& password) {
    if (!db.isOpen() && !db.open()) {
        qDebug() << "Database connection failed during login: " << db.lastError().text();
        return QString();  // 返回空字符串表示失败
    }

    QSqlQuery query(db);
    query.prepare("SELECT id, password FROM users WHERE username = ?");
    query.addBindValue(username);

    if (!query.exec() || !query.next()) {
        qDebug() << "登录失败，用户名不存在或数据库查询失败";
        return QString();
    }

    QString storedPassword = query.value(1).toString();
    QString hashedInputPassword = hashPassword(password);  // Hash the input password

    if (storedPassword == hashedInputPassword) {
        QString userID = query.value(0).toString();
        qDebug() << "登录成功, 用户ID: " << userID;
        return userID;  // 返回 userID
    } else {
        qDebug() << "登录失败，用户名或密码错误";
        return QString();
    }
}



bool AccountManager::userExists(const QString& username) {
    if (!db.isOpen() && !db.open()) {
        qDebug() << "Database connection failed during user existence check: " << db.lastError().text();
        return false;
    }

    QSqlQuery query(db);
    query.prepare("SELECT COUNT(*) FROM users WHERE username = ?");
    query.addBindValue(username);

    if (!query.exec()) {
        qDebug() << "用户查询失败: " << query.lastError().text();
        return false;
    }

    if (!query.next()) {
        qDebug() << "用户查询失败，没有返回结果";
        return false;
    }

    int userCount = query.value(0).toInt();
    qDebug() << "用户存在数量: " << userCount;

    return userCount > 0;
}

QString AccountManager::hashPassword(const QString& password) {
    return QString(QCryptographicHash::hash(password.toUtf8(), QCryptographicHash::Sha256).toHex());
}

bool AccountManager::verifyPassword(const QString& storedPassword, const QString& providedPassword) {
    return hashPassword(providedPassword) == storedPassword;}
